﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Web.UI;

namespace DesignLife.Admin
{
    public partial class AdminLogin : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        DataTable tb = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lblError.Visible = false;
                txtuser.Focus();
            }
        }

        protected void tmbdangnhap_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["Design_LifeConnection"].ConnectionString;
                cmd.Connection = conn;
                cmd.CommandText = "SELECT dbo.Users.*, dbo.Roles.RoleID, dbo.Roles.RoleName FROM dbo.Roles INNER JOIN dbo.Users ON dbo.Roles.RoleID = dbo.Users.IDRole";
                cmd.CommandType = CommandType.Text;
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        if (txtuser.Text == reader["Username"].ToString() && txtpass.Text == reader["Password"].ToString() && bool.Parse(reader["Status"].ToString()) == true)
                        {
                            if (Application["ses"] != null)
                            {
                                ((HttpSessionState)Application["ses"]).Clear();
                            }

                            lblError.Text = "";
                            if (reader["RoleName"].ToString() == "Admin")
                            {
                                Session["Role"] = "1";
                            }
                            Session["Username"] = txtuser.Text;
                            Session["Fullname"] = reader["Fullname"].ToString();
                            Application["ses"] = Session;
                            Response.Redirect("UserManager.aspx");
                        }
                    }
                }
                conn.Close();
            }
            catch
            {
                lblError.Visible = true;
                lblError.Text = "Login failed !";
            }
            lblError.Visible = true;
            lblError.Text = "Login failed !";
        }
    }
}